'use strict';

const Controller = require('egg').Controller;

const {createToken,createCode}=require("../utils/utils")

class HomeController extends Controller {

  // 查询
  async show(){
    const {ctx}=this
    const {id}=ctx.params
    const result=await ctx.service.user.showService(id)
    if(result.length){
      ctx.body={
        code:"1001",
        msg:"查看数据成功",
        result
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"查看数据失败"
      }
    }
  }

  // 编辑
  async update(){
    const {ctx}=this
    const {id}=ctx.params
    const {username,nickname}=ctx.request.body
    const result=await ctx.service.user.updateService(id,username,nickname)
    if(result.affectedRows){
      ctx.body={
        code:"1001",
        msg:"编辑成功"
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"编辑失败"
      }
    }
  }

  // 删除;
  async destroy(){
    const {ctx}=this
    const {id}=ctx.params
    const result=await ctx.service.user.delService(id)
    if(result.affectedRows){
      ctx.body={
        code:"1001",
        msg:"删除成功"
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"删除失败"
      }
    }
  }

  // 增加
  async create(){
    const {ctx}=this
    const {username,nickname}=ctx.request.body
    const result=await ctx.service.user.createServie(username,nickname)
    if(result.affectedRows){
      ctx.body={
        code:"1001",
        msg:"增加成功"
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"增加失败"
      }
    }
  }

  // 获取数据
  async index(){
    const {ctx}=this
    const result=await ctx.service.user.indexService()
    if(result.length){
      ctx.body={
        code:"1001",
        msg:"获取数据成功",
        result
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"获取数据失败"
      }
    }
  }

  // 获取验证码
  async getCode(){
    const {ctx}=this
    const code=createCode()
    ctx.session.code=code.text
    ctx.body={
      code:"1001",
      msg:"获取验证码成功"
    }
  }

  // 注册
  async registryController(){
    const {ctx}=this
    const {username,pwd}=ctx.request.body
    const flag=await ctx.service.user.changeName(username)
    if(!flag){
      const result=await ctx.service.user.registryService(username,pwd)
      if(result.affectedRows){
        ctx.body={
          code:"1001",
          msg:"注册成功"
        }
      }else{
        ctx.body={
          code:"1002",
          msg:"注册失败"
        }
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"该用户名已注册"
      }
    }
  }

  // 登录
  async loginController() {
    const { ctx } = this;
    const {username,pwd}=ctx.request.body
    const result=await ctx.service.user.loginService(username,pwd)
    if(result.length){
      const token=createToken(result[0].id)
      ctx.body={
        code:"1001",
        msg:"登录成功",
        token
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"登录失败"
      }
    }
  }
}

module.exports = HomeController;
